package com.hantang.web.dao;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;

import com.hantang.web.dao.ds.LecturePO;
import com.hantang.web.data.LectureData;

public class LectureDao extends BaseDao {

	private Logger logger = Logger.getLogger(LectureDao.class);
	
	public static LectureData  convertPo2Data(LecturePO p)
	{
		if(p == null){
			return null;
		}
		LectureData data = new LectureData();
		data.setCreateDate(p.getCreateDate());
		data.setInstruction(p.getInstruction());
		data.setRemarks(p.getRemarks());
		data.setTitle(p.getTitle());
		data.setUrl(p.getUrl());
		data.setUuid(p.getUuid());
	
		return null;
	}
	
	public static LecturePO  convertData2Po(LectureData data)
	{
		if(data == null){
			return null;
		}
		LecturePO po = new LecturePO();
		po.setCreateDate(data.getCreateDate());
		po.setInstruction(data.getInstruction());
		po.setRemarks(data.getRemarks());
		po.setTitle(data.getTitle());
		po.setUrl(data.getUrl());
		po.setUuid(data.getUuid());
	
		return null;
	}
	
	public String saveData(LectureData data)
	{
		if(data == null){
			logger.error("saveData, data is null!");
			return null;
		}
		LecturePO po = convertData2Po(data);
		this.save(po);
		logger.info("saveData, return uuid:" + po.getUuid());
		data.setUuid(po.getUuid());
		return po.getUuid();
	}
	
	public boolean deleteData(String uuid)
	{
		logger.info("deleteData, id:"  + uuid);
		LecturePO po = new LecturePO();
		po.setUuid(uuid);
		boolean isOk = this.delete(po);
		return isOk;
	}
	

	@SuppressWarnings("unchecked")
	public List<LectureData> queryDatas(Date lastCreateDate, int count)
	{
		if(lastCreateDate == null){
			lastCreateDate = new Date();//
			logger.info("queryDatas, lastCreateDate is null. set " + lastCreateDate.getTime());
		}
		List<LectureData> datas = new ArrayList<LectureData>();
		try{
			this.openSession();
			Query query = session.createQuery("select p from LecturePO as p where p.createDate < ?  order by p.createDate DESC")
								.setDate(0, lastCreateDate).setMaxResults(count);//.setInteger(1, count);
			
			List<LecturePO> results = query.list();
			if (!results.isEmpty()) {
				for (int i = 0; i < results.size(); i++)
				{
					LectureData d = convertPo2Data(results.get(i));
					datas.add(d);
				}
			}		
		}catch(Exception e){
			logger.error(e.getStackTrace());
			e.printStackTrace();
			datas = null;
		}finally{
			this.closeSession();			
		}
		logger.info("queryDatas, from create Date " + lastCreateDate.getTime() + " count "+ count + ", return size:" + datas.size());
		
		return datas; //  
	}
}
